/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import { exportQAHistories } from "@/services/download";
import qs from "qs";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import { Card, Row, Col, Form, Input, Button, message, Icon, Checkbox, Table, Tag, Select, Modal, Radio, Spin, Upload, Tabs, } from "antd";
import Custom from "./custom.js";
import CustomNew from "./customNew";
import { routerRedux } from "dva/router";
import BackRouter from "@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter";

const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from "./index.less";
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from "../../../assets/icons/bi.png";
import ljx from "../../../assets/icons/垃圾箱.png";

class NoEnumerationNew extends Component {
	constructor(props) {
		super(props);
		const { id, urlPrefix } = this.props.match.params;
		this.state = {
			okname: id
				? this.props.location.query.name
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[1]),
			disabled: true,
			name: id
				? this.props.location.query.name
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[1]),
			okid: id
				? this.props.location.query.id
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[0]),
			mockValue: "",
			listday: [],
			dataSource2: [],
			totab: [],
			login: false,
			urlPrefix,
		};
	}

	componentDidMount() {
		this.fetchb();
	}

	fetchb = () => {
		this.setState({ login: true, });
		const { dispatch, currentUser } = this.props;
		const { okid, page, limit, itemNames, urlPrefix } = this.state;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/unEnumList",
				payload: { modelId: okid, urlPrefix },
				callback: (res) => {
					let a = res.records ? res.records : [];
					a.map((item, index) => {
						item["key"] = index;
					});
					this.setState({ dataSource2: a, listday: a, login: false, });
				},
			});
		});
	};

	returnButton = () => {
		return (
			<BackRouter style={{ float: "right" }} pathname='/knowledgeDesign/customDictionary'></BackRouter>
		);
	};

	returnHome = () => {
		const { dispatch } = this.props;
		dispatch(routerRedux.push({ pathname: "/knowledgeDesign/customDictionary", }));
	};

	// 新增
	handleSubmitC = () => {
		let arr = this.state.listday;
		let dictItems = { type: 0, content: "", };
		arr.push(dictItems);
		this.setState({ listday: arr, });
	};

	busChanges = (value, index) => {
		let arr = this.state.listday;
		arr[index].type = value;
	};

	//删除
	handleSubmitA = (index) => {
		let arr = this.state.listday;
		arr.splice(index, 1);

		this.setState({ listday: arr, });
	};

	busChange = (e, index) => {
		let arr = this.state.listday;
		arr[index].content = "";
		arr[index].content = e.target.value;
		this.setState({ listday: arr, });
	};

	handleSubmitB = () => {
		const { dispatch } = this.props;
		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/fetchh",
				payload: { modelId: this.state.okid, data: this.state.listday },
				callback: (res) => {
					message["info"](`${res.message}`);
					this.fetchb();
				},
			});
		});
	};

	checkField(rule, value, callback) {
		const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
		if (rule.field === "namecid") {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 20 || value.length < 0) {
						callback("支持20位以内大小写字母、数字和中文");
					} else {
						callback();
					}
				} else {
					callback("支持20位以内大小写字母、数字和中文");
				}
			} else {
				callback("支持20位以内大小写字母、数字和中文");
			}
		}
	}

	// 词典名称修改
	textInput = () => {
		const { getFieldDecorator } = this.props.form;
		const { urlPrefix } = this.state;

		return (
			<div className={styles.flexcen}>
				<Form layout='inline' onSubmit={this.handleSubmit}>
					<FormItem label='实体名称'>
						{getFieldDecorator("namecid", {
							initialValue: this.state.name,
							rules: [
								{ required: true, message: "实体名称必填", },
								{ validator: this.checkField },
							],
						})(
							<Input defaultValue={this.state.name} disabled={this.state.disabled} onPressEnter={this.saveChanges} onChange={this.namegai} />
						)}
					</FormItem>
					{this.state.disabled === true ? (
						urlPrefix ? null : (
							<span>
								<Icon onClick={this.modifyClick} className={styles.fleximg} type='edit' />
							</span>
						)
					) : (
						<span>
							<Icon onClick={this.bcClick} className={styles.fleximg} type='check' />
						</span>
					)}
				</Form>
			</div>
		);
	};

	namegai = (e) => {
		this.setState({ mockValue: e.target.value });
	};

	// 字典名称显示或隐藏
	modifyClick = () => {
		this.setState({ disabled: false, });
	};

	bcClick = () => {
		if (this.state.mockValue === "") {
			// message['warning']('未修改')

			this.setState({ disabled: true, });

			const { dispatch } = this.props;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "customDictionary/fetche",
					payload: { id: this.state.okid, name: this.state.okname },
					callback: (res) => {
						message["info"](`${res.message}`);
					},
				});
			});
		} else {
			this.setState({ disabled: true, });
			// message['success']('修改成功')
			// 可枚举页 修改词典

			const { dispatch } = this.props;
			this.reqRef = requestAnimationFrame(() => {
				dispatch({
					type: "customDictionary/fetche",
					payload: { id: this.state.okid, name: this.state.mockValue },
					callback: (res) => {
						message["info"](`${res.message}`);
					},
				});
			});
		}
	};

	// eslint-disable-next-line react/sort-comp
	render() {
		const { urlPrefix } = this.state;
		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<div className={styles.backgroundp}>
						<Row className={styles.colorBackground}>
							<Col style={{ padding: 10 }} xs={24} className={styles.colorA}>
								<span className={styles.title}>
									<span>实体详情</span>
									{this.returnButton()}
								</span>
							</Col>
						</Row>
						{this.textInput()}
						<Card bordered={false}>
							<Spin spinning={this.state.login}>
								{urlPrefix ? null : (
									<Button style={{ marginBottom: 18 }} type='primary' onClick={this.handleSubmitC} icon='plus'>
										<FormattedMessage id='app.customDictionary.add-new-format' defaultMessage='Rank' />
									</Button>
								)}

								{this.state.listday.map((item, index) => {
									return (
										<Spin spinning={this.state.login}>
											<Form layout='inline' style={{ marginBottom: 10 }}>
												<FormItem>
													<Select style={{ width: 160 }} defaultValue={item.type ? item.type : 0} onChange={(e) => this.busChanges(e, index)}>
														<Option value={1}>
															<FormattedMessage id='app.customDictionary.regular-expression' defaultMessage='Regular expression' />
														</Option>
														<Option value={0}>
															<FormattedMessage id='app.customDictionary.placeholder' defaultMessage='placeholder' />
														</Option>
													</Select>
												</FormItem>
												<FormItem>
													<Input style={{ width: 354 }} value={item.content} onChange={(e) => this.busChange(e, index)}></Input>
												</FormItem>
												{urlPrefix ? null : (
													<FormItem>
														<span> <img src={ljx} onClick={() => this.handleSubmitA(index)} /> </span>
													</FormItem>
												)}
											</Form>
										</Spin>
									);
								})}
								<div>
									{urlPrefix ? null : (
										<Button style={{ background: "#19c3f3", color: "#ffffff", marginTop: 18, }} onClick={this.handleSubmitB}>保存</Button>
									)}
								</div>
								<div className={styles.textOne}>
									<div style={{ padding: "20px 30px 40px 30px" }}>
										<h5 style={{ fontWeight: "bold" }}> <FormattedMessage id='app.customDictionary.enumeration-texta' /> </h5>
										<p> <FormattedMessage id='app.customDictionary.enumeration-textb' /> </p>
										<p> <FormattedMessage id='app.customDictionary.enumeration-textc' /> </p>
										<p>{'可用 ？代表单个数字/字母，* 代表任意多个(>=1)数字/字母'}</p>
										<h5 style={{ fontWeight: "bold" }}> <FormattedMessage id='app.customDictionary.enumeration-textd' /> </h5>
										<p>{'按照标准的正则表达式语法编写即可，具体语法可参考：正则表达式介绍'}</p>
										<p style={{ lineHeight: 2 }}>
											<span style={{ fontWeight: 700 }}>注:</span>
											此处的正则表达式不支持使用大写字母。(因为对于用户输入的内容，系统会先将其中的大写字母都转换成小写，然后再进行识别抽取，因此如果用大写字母的话会造成系统无法识别。)
										</p>
									</div>
								</div>
							</Spin>
						</Card>
					</div>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	// 全局数据
	currentUser: user.currentUser,
}))(Form.create()(NoEnumerationNew));
